/**
 * 完成视频中后课后作业写的小工具，计算机器码的操作数对应的 rotate 和 immediate
 *   rotate: 循环右移的次数(4位)
 *   immediate: 立即数数值(8位)
 * 
 * 通过反汇编，查询对应机器码，更改bin文件机器码，点亮LED2
*/

#include <stdio.h>
#include <stdlib.h>

unsigned int ror(unsigned int val, int bit)
{
    unsigned res = val >> bit;
    res |= val << (32 - bit);

    return res;
}

void to_binary(unsigned long num)
{
    int r;

    r = num % 2;

    if (num >= 2)
    {
        to_binary(num / 2);
    }

    putchar(r + '0');
}

int main(int argc, char **argv)
{

    if (argc < 2)
    {
        printf("Usage: %s <shifter operand>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int shifter_operand = atoi(argv[1]);
    printf("shifter_operand %d\n", shifter_operand);

    int rotate = 0;
    int immediate = 0;

    int i, j, flag = 0;
    for (i = 0; i <= 15; ++i)
    {
        for (j = 0; j <= 255; ++j)
        {
            if (shifter_operand == ror(i, 2 * j))
            {
                rotate = i;
                immediate = j;
                flag = 1;
                break;
            }
        }

        if (flag)
        {
            break;
        }
    }

    printf("rotate: ");
    to_binary(rotate);
   
    printf("\nimmediate: ");
    to_binary(immediate);
  
    printf("\n");

    return 0;
}
